<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Validate;
use tree\Tree;

class Index extends Controller
{
    public function _initialize()
    {
        if (!in_array(Request()->action(true), ['login', 'confirmLogin', 'loginOut', 'checkAndSendSms', 'register', 'resetPassword'])) {
            $user_id = Session('login_info');
            if (empty($user_id)) echo "<script>window.location.href='/index/index/login'</script>";
        }
    }

    /**
     * 登录
     * */
    public function login()
    {
        $this->assign('is_login', (bool)Session('login_info'));
        return $this->fetch();
    }

    public function confirmLogin()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $password = $input['password'];

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (empty($password)) apiReturn(2, '请输入密码');

        $info = Db::name('user')->where(['mobile' => $mobile, 'user_type' => 2])->find();
        if ($info) {
            if ($info['password'] != thinkEncrypt($password)) apiReturn(2, '密码错误');

            $data = [
                'user_id' => $info['id'],
                'avatar' => doAvatar($info['avatar']),
                'mobile' => hideMobile($info['mobile'])
            ];

            Session('login_info', $data);

            apiReturn(1, '登录成功');
        } else {
            apiReturn(2, '账号不存在或已被禁用');
        }
    }

    /**
     * 退出登录
     * */
    public function loginOut()
    {
        Session('login_info', null);
    }

    /**
     * 获取验证码
     * */
    public function checkAndSendSms()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $captcha = $input['captcha'];
        $type = $input['type'] ? : 'resetPwd';

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (empty($captcha)) apiReturn(2, '请输入图形验证码');

        $sms_account = C('SMS_ACCOUNT');
        $sms_password = C('SMS_PASSWORD');

        if (empty($sms_account)) apiReturn(2, '短信平台账号未配置');
        if (empty($sms_password)) apiReturn(2, '短信平台密码未配置');

        if (!captcha_check($captcha)) apiReturn(2, '图形验证码错误');

        if ($type == 'resetPwd') {
            $count = Db::name('user')->where(['mobile' => $mobile, 'user_type' => 2])->count();
            if ($count == 0) apiReturn(2, '手机号不存在');
        } else {
            $count = Db::name('user')->where(['mobile' => $mobile])->count();
            if ($count) apiReturn(2, '手机号已注册');
        }

        $time = time();

        //获取手机号
        $pattern = "/^1[0123456789]\d{9}$/";
        if (preg_match($pattern, $mobile)) {
            $result = Db::name('sms_code')->where(['mobile' => $mobile])->order('create_time desc')->find();
            $result = $time - $result['create_time'];
            if ($result < 60 && $result > 0) apiReturn(2, '当前手机号操作频繁,请60秒后发送');

            $code = rand(100000, 999999);
            $statusStr = [
                "0" => 1,
                "-1" => "参数不全",
                "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                "30" => "密码错误",
                "40" => "账号不存在",
                "41" => "余额不足",
                "42" => "帐户已过期",
                "43" => "IP地址限制",
                "50" => "内容含有敏感词"
            ];
            $smsapi = "http://api.smsbao.com/";
            $content = "【班众】您的验证码是{$code}。如非本人操作，请忽略本短信"; // 要发送的短信内容
            $url = $smsapi . "sms?u=" . $sms_account . "&p=" . md5($sms_password) . "&m=" . $mobile . "&c=" . urlencode($content);
            $result = file_get_contents($url);
            if ($result == 0) {
                Db::name('sms_code')->where("`mobile` = '{$mobile}' AND ( `status` = 1 OR `failure_time` < {$time} )")->setField('status', 0);

                $info['code'] = $code;
                $info['mobile'] = $mobile;
                $info['create_time'] = $time;
                $info['failure_time'] = $time + 600;//失效时间：10分钟
                Db::name('sms_code')->insert($info);

                apiReturn(1, '短信发送成功');
            } else {
                apiReturn(2, $statusStr[$result]);
            }
        } else {
            apiReturn(2, '手机号码格式错误');
        }
    }

    /**
     * 注册
     * */
    public function register()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $code = $input['code'];
        $password = $input['password'];
        $again_password = $input['again_password'];

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (empty($code)) apiReturn(2, '请输入验证码');
        if (empty($password)) apiReturn(2, '请输入密码');
        if (empty($again_password)) apiReturn(2, '请重复输入密码');
        if ($password !== $again_password) apiReturn(2, '两次密码不一致，请重新输入');

        $time = time();

        $count = Db::name('user')->where(['mobile' => $mobile])->count();
        if ($count) apiReturn(2, '手机号已注册');

        $code_info = Db::name('sms_code')->where(['mobile' => $mobile])->order('id desc')->find();
        if (empty($code_info) || $code_info['code'] != $code) apiReturn(2, '验证码错误');
        if ($code_info['status'] == 0 || $code_info['failure_time'] < $time) apiReturn(2, '验证码已失效');

        $data = [
            'mobile' => $mobile,
            'password' => thinkEncrypt($password),
            'user_type' => 2,
            'create_time' => $time
        ];
        $res = Db::name('user')->insert($data);
        if ($res) {
            apiReturn(1, '注册成功');
        } else {
            apiReturn(2, '注册失败');
        }
    }

    /**
     * 重置密码
     * */
    public function resetPassword()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $code = $input['code'];
        $new_password = $input['new_password'];
        $again_password = $input['again_password'];

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (empty($code)) apiReturn(2, '请输入验证码');
        if (empty($new_password)) apiReturn(2, '请输入新密码');
        if (empty($again_password)) apiReturn(2, '请重复输入新密码');
        if ($new_password !== $again_password) apiReturn(2, '两次密码不一致，请重新输入');

        $time = time();

        $count = Db::name('user')->where(['mobile' => $mobile, 'user_type' => 2])->count();
        if ($count == 0) apiReturn(2, '手机号不存在');

        $code_info = Db::name('sms_code')->where(['mobile' => $mobile])->order('id desc')->find();
        if (empty($code_info) || $code_info['code'] != $code) apiReturn(2, '验证码错误');
        if ($code_info['status'] == 0 || $code_info['failure_time'] < $time) apiReturn(2, '验证码已失效');

        $data = [
            'password' => thinkEncrypt($new_password),
            'update_time' => $time
        ];
        $res = Db::name('user')->where(['mobile' => $mobile])->update($data);
        if ($res) {
            apiReturn(1, '重置密码成功');
        } else {
            apiReturn(2, '重置密码失败');
        }
    }

    /**
     * 首页
     * */
    public function index()
    {
        $input = Request()->param();

        $ppt_file_index = $input['ppt_file_index'] ? : '';
        $ppt_page = $input['ppt_page'] ? : '';
        $course_id = $input['course_id'] ? : 0;

        if ($ppt_file_index && $ppt_page) {
            $again_study_preview_ppt_url = doPreviewPptUrl($ppt_file_index, $ppt_page);
            $this->assign('again_study_preview_ppt_url', $again_study_preview_ppt_url);
            $this->assign('again_course_id', $course_id);
        }

        $category_list = Db::name('category')->field('id,pid,name')->where(['type' => 1])->order('sort asc, id asc')->select();
        $course_list = Db::name('course')->field('id,category_ids pid,title name,ppt_file_index')->order('sort asc')->select();
        $knowledge_list = [];
        if ($course_list) {
            foreach ($course_list as $k => &$v) {
                $course_id = $v['id'];
                $v['id'] = '999999999' . $course_id;
                if ($pid = $v['pid']) {
                    $pid_arr = explode(',', $pid);
                    $v['pid'] = $pid_arr[count($pid_arr) - 1];


                    $course_knowledge_list = Db::name('course_knowledge')->field('id,name,ppt_start_page,ppt_end_page')->where(['course_id' => $course_id])->order('sort asc')->select();
                    if ($course_knowledge_list) {
                        foreach ($course_knowledge_list as $key => &$val) {
                            $knowledge_list[] = [
                                'id' => 'knowledge_' . $val['ppt_start_page'] . '_' . $val['ppt_end_page'] . '_' . $course_id . '_' . $key,
                                'pid' => $v['id'],
                                'name' => $val['name'],
                                'preview_ppt_url' => doPreviewPptUrl($v['ppt_file_index'], $val['ppt_start_page'])
                            ];
                        }
                    }

                    unset($course_list[$k]['ppt_knowledge']);
                    unset($course_list[$k]['ppt_file_index']);
                } else {
                    unset($course_list[$k]);
                }
            }
        }
        //        echo "<pre>";
        //        print_r(array_merge($category_list, $course_list, $knowledge_list));
        //        exit;
        $this->assign('tree', json_encode(array_merge($category_list, $course_list, $knowledge_list), JSON_UNESCAPED_UNICODE));
        $this->assign('position_title', '平台首页');

        return $this->fetch();
    }

    /**
     * 获取课程信息
     * */
    public function getCourseInfo()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '课程ID缺失');

        $info = Db::name('course')->where(['id' => $id])->find();
        if ($info) {
            $info['img'] = getPicture($info['img']);
            $info['ppt_preview_url'] = doPreviewPptUrl($info['ppt_file_index']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '课程不存在或已删除');
        }
    }

    /**
     * 获取某一个用户浏览某一个PPT可以达到的最大页数
     * */
    public function getEndPptPage()
    {
        $input = Request()->param();

        $user_id = session('login_info.user_id');
        $course_id = $input['course_id'];

        if (empty($course_id)) apiReturn(2, '课程ID缺失');

        $knowledge_id = Db::name('topic_complete_log')->where(['user_id' => $user_id, 'course_id' => $course_id])->order('id desc')->value('knowledge_id');
        if ($knowledge_id) {
            $ppt_end_page = Db::name('course_knowledge')->where(['course_id' => $course_id, 'id' => ['gt', $knowledge_id]])->value('ppt_end_page');
        } else {
            $ppt_end_page = Db::name('course_knowledge')->where(['course_id' => $course_id])->order('id asc')->value('ppt_end_page');
        }

        apiReturn(1, '获取数据成功', $ppt_end_page ? : 0);
    }

    /**
     * 获取练习题信息
     * */
    public function getTopicInfo()
    {
        $input = Request()->param();

        $user_id = session('login_info.user_id');
        $course_id = $input['course_id'];
        $ppt_page = $input['ppt_page'];

        if (empty($course_id)) apiReturn(2, '课程ID缺失');

        $do_topic_count = C('GET_TOPIC_COUNT');// 练习题数量
        if ($do_topic_count <= 0) apiReturn(2, '请前往后台配置【练习题数量】');

        $knowledge_id = 0;
        $topic_ids = [];
        $knowledge_list = Db::name('course_knowledge')->where(['course_id' => $course_id])->order('sort asc')->select();
        foreach ($knowledge_list as $v) {
            if ($v['ppt_end_page'] == $ppt_page) {
                $topic_ids = $v['topic_ids'] ? explode(',', $v['topic_ids']) : [];
                $knowledge_id = $v['id'];
                continue;
            }
        }

        // 查询本知识点是否做题完成
        if ($knowledge_id) {
            $count = Db::name('topic_complete_log')->where(['user_id' => $user_id, 'course_id' => $course_id, 'knowledge_id' => $knowledge_id])->count();
            if ($count) apiReturn(2, '该知识点做题已完成');
        }

        $info = Db::name('course')->where(['id' => $course_id])->find();
        if ($info) {
            if ($topic_ids) {
                shuffle($topic_ids);                                     // 打乱顺序
                $topic_ids = array_slice($topic_ids, 0, $do_topic_count);// 取出前几项

                $topic_ids_str = implode(',', $topic_ids);

                $sql = "SELECT * FROM `study_topic` WHERE `id` IN (" . $topic_ids_str . ") ORDER BY FIELD(`id`, " . $topic_ids_str . ")";
                $topic_list = Db::name('topic')->query($sql);

                $group_topic_list = [];

                if ($topic_list) {
                    foreach ($topic_list as $k => &$v) {
                        if ($v['type'] == 2) {
                            // 组合题
                            $list = getGroupTopics($v['id']);
                            $group_topic_list[] = [
                                'key' => $k,
                                'list' => $list
                            ];
                            unset($topic_list[$k]);
                        } else {
                            $question = json_decode($v['question'], true);
                            $question['text'] = $question['text'] ? : '如图所示';
                            $question['img'] = getPicture($question['img']);
                            $v['question'] = $question;

                            $option = json_decode($v['option'], true);
                            if ($v['option_type'] == 2) {
                                foreach ($option as &$val) {
                                    $val['value'] = getPicture($val['value']);
                                }
                            }
                            $v['option'] = $option;
                        }
                    }
                }

                $topic_list = array_merge($topic_list);
                if ($group_topic_list) {
                    $prev_group_topic_list_len = 0;
                    foreach ($group_topic_list as $k => &$v) {
                        if ($k > 0) $prev_group_topic_list_len = count($group_topic_list[$k - 1]);
                        array_splice($topic_list, $v['key'] + $k + $prev_group_topic_list_len, 0, $v['list']);
                    }
                }

                $data = [
                    'knowledge_id' => $knowledge_id,
                    'topic_list' => $topic_list,
                    'topic_ids' => array_column($topic_list, 'id')
                ];

                apiReturn(1, '获取数据成功', $data);
            } else {
                apiReturn(2, '无练习题');
            }
        } else {
            apiReturn(2, '课程不存在或已删除');
        }
    }

    public function getLiteratureCount()
    {
        $input = Request()->param();

        $course_id = $input['course_id'];
        $ppt_page = $input['ppt_page'];

        if ($course_id && $ppt_page) {
            $count = Db::name('literature')->where(['course_id' => $course_id, 'ppt_page' => $ppt_page])->count();
            if($count){
                apiReturn(1, '有文献');
            }else{
                apiReturn(2, '无文献');
            }
        } else {
            apiReturn(2, '无文献');
        }
    }

    /**
     * 练习题提交答案
     * */
    public function topicSubmit()
    {
        $input = Request()->param();

        $user_id = session('login_info.user_id');
        $id = $input['id'];
        $knowledge_id = $input['knowledge_id'] ? : '';
        $me_answer = $input['me_answer'];
        $course_id = $input['course_id'];
        $ppt_page = $input['ppt_page'];
        $submit_do_topic_ids = $input['submit_do_topic_ids'];
        $submit_complete_topic_ids = $input['submit_complete_topic_ids'];

        if (empty($id)) apiReturn(2, '题目ID缺失');
        if (empty($me_answer)) apiReturn(2, '请选择选项');
        if (empty($course_id)) apiReturn(2, '课程ID缺失');

        $do_topic_ids = explode(',', $submit_do_topic_ids);
        $complete_topic_ids = explode(',', $submit_complete_topic_ids);

        $topic_info = Db::name('topic')->where(['id' => $id])->find();
        if ($topic_info) {
            Db::startTrans();
            try {
                $knowledge_name = Db::name('course_knowledge')->where(['id' => $knowledge_id])->value('name');
                $knowledge_name = $knowledge_name ? : '';

                $time = time();

                $category_ids = Db::name('course')->where(['id' => $course_id])->value('category_ids');
                $category_ids_arr = explode(',', $category_ids);
                $category_id = end($category_ids_arr);

                if (count($do_topic_ids) >= count($complete_topic_ids)) {
                    // 完成本知识点的学习，记录学习记录
                    $course_log_data = [
                        'user_id' => $user_id,
                        'category_id' => $category_id,
                        'course_id' => $course_id,
                        'knowledge_id' => $knowledge_id,
                        'ppt_page' => $ppt_page,
                        'study_time' => $time
                    ];
                    Db::name('course_log')->insert($course_log_data);

                    // 记录做题完成记录
                    $topic_complete_log_data = [
                        'user_id' => $user_id,
                        'course_id' => $course_id,
                        'knowledge_id' => $knowledge_id
                    ];
                    Db::name('topic_complete_log')->insert($topic_complete_log_data);
                }

                $true_answer = '';
                foreach (json_decode($topic_info['option'], true) as &$v) {
                    if ($v['answer']) {
                        if ($true_answer == '') {
                            $true_answer = $v['key'];
                        } else {
                            $true_answer .= ',' . $v['key'];
                        }
                    }
                }
                $is_true = $me_answer != $true_answer ? 0 : 1;

                if ($topic_info['type'] == 3) {
                    $question_stem = Db::name('topic')->where(['id' => $topic_info['pid']])->value('question_stem');
                } else {
                    $question_stem = '';
                }

                $category_ids = Db::name('course')->where(['id' => $course_id])->value('category_ids');
                $category_ids_arr = explode(',', $category_ids);
                $category_id = end($category_ids_arr);

                $log_data = [
                    'course_id' => $course_id,
                    'category_id' => $category_id,
                    'user_id' => $user_id,
                    'topic_id' => $id,
                    'question_stem' => $question_stem,
                    'question' => $topic_info['question'],
                    'option' => $topic_info['option'],
                    'option_type' => $topic_info['option_type'],
                    'analysis' => $topic_info['analysis'],
                    'style' => $topic_info['style'],
                    'type' => $topic_info['type'],
                    'is_true' => $is_true,
                    'me_answer' => $me_answer,
                    'create_time' => $time
                ];
                Db::name('topic_log')->insert($log_data);

                $census_info = Db::name('topic_census')->where(['course_id' => $course_id, 'topic_id' => $id])->find();
                if ($census_info) {
                    $do_count = $census_info['do_count'] + 1;
                    $true_count = $is_true ? $census_info['true_count'] + 1 : $census_info['true_count'];
                    $true_rate = sprintf('%.2f', ($true_count / $do_count) * 100);
                    $error_count = !$is_true ? $census_info['error_count'] + 1 : $census_info['error_count'];
                    $error_rate = 100 - $true_rate;

                    $census_data = [
                        'do_count' => $do_count,
                        'true_count' => $true_count,
                        'true_rate' => $true_rate,
                        'error_count' => $error_count,
                        'error_rate' => $error_rate,
                        'update_time' => $time
                    ];
                    Db::name('topic_census')->where(['id' => $census_info['id']])->update($census_data);
                } else {
                    if ($is_true) {
                        $true_count = 1;
                        $true_rate = 100;
                        $error_count = 0;
                        $error_rate = 0;
                    } else {
                        $true_count = 0;
                        $true_rate = 0;
                        $error_count = 1;
                        $error_rate = 100;
                    }
                    $census_data = [
                        'course_id' => $course_id,
                        'topic_id' => $id,
                        'do_count' => 1,
                        'true_count' => $true_count,
                        'true_rate' => $true_rate,
                        'error_count' => $error_count,
                        'error_rate' => $error_rate,
                        'update_time' => $time
                    ];
                    Db::name('topic_census')->insert($census_data);
                }

                if ($is_true) {
                    $img_arr = ['emoji_aixin.png', 'emoji_dianzan.png', 'emoji_paishou.png', 'emoji_weixiao.png', 'emoji_xianhua.png'];
                    $text = '恭喜您！答对了';
                    // 积分录入数据
                    $msg = $knowledge_name ? $knowledge_name . '，做题正确' : '做题正确';
                    $type = 1;
                    // 用户积分变化
                    Db::name('user')->where(['id' => $user_id])->setInc('integral');
                } else {
                    $img_arr = ['emoji_cuowu.png', 'emoji_kulian.png', 'emoji_touyun.png', 'emoji_zhadan.png', 'emoji_zheduan.png'];
                    $text = '很遗憾！答错了';
                    // 积分录入数据
                    $msg = $knowledge_name ? $knowledge_name . '，做题错误' : '做题错误';
                    $type = 2;
                    // 用户积分变化
                    Db::name('user')->where(['id' => $user_id])->setDec('integral');
                }

                // 积分数据录入
                $integral_log = [
                    'user_id' => $user_id,
                    'msg' => $msg,
                    'integral' => 1,
                    'type' => $type,
                    'create_time' => $time
                ];
                Db::name('integral_log')->insert($integral_log);

                $data = [
                    'is_true' => $is_true,
                    'answer_img' => $img_arr[array_rand($img_arr)],
                    'answer_text' => $text
                ];

                Db::commit();
                apiReturn(1, '提交成功', $data);
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '提交失败');
            }
        } else {
            apiReturn(2, '题目不存在或已删除');
        }
    }

    /**
     * 获取课程参考文献
     * */
    public function getLiteratureList()
    {
        $input = Request()->param();

        $title = $input['title'];

        $course_id = $input['course_id'];
        $ppt_page = $input['ppt_page'];

        if (empty($course_id)) apiReturn(2, '课程ID缺失');

        $where['course_id'] = $course_id;
        if ($title) $where['title'] = ['LIKE', '%' . $title . '%'];
        if ($ppt_page) $where['ppt_page'] = $ppt_page;

        $list = Db::name('literature')->where($where)->select();
        if ($list) {
            foreach ($list as &$v) {
                $desc = doEditorContent($v['desc']);
                $v['desc'] = htmlspecialchars_decode($desc);

            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 学习记录
     * */
    public function studyLogList()
    {
        $input = Request()->param();

        $user_id = session('login_info.user_id');
        $knowledge_name = $input['knowledge_name'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 9;

        $where['l.user_id'] = $user_id;
        if ($knowledge_name) $where['k.name'] = ['LIKE', '%' . $knowledge_name . '%'];

        $list = Db::name('course_log l')->join('study_course_knowledge k', 'l.knowledge_id = k.id', 'left')
            ->field('l.course_id,k.name,l.ppt_page,l.study_time')
            ->where($where)->order('study_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['ppt_file_index'] = Db::name('course')->where(['id' => $v['course_id']])->value('ppt_file_index');
            }
        }
        $this->assign('list', $list);

        $count = Db::name('course_log l')->join('study_course_knowledge k', 'l.knowledge_id = k.id', 'left')->where($where)->count();
        $all_page = ceil($count / $pagesize);
        $this->assign('all_page', $all_page);


        $this->assign('position_title', '学习中心');
        return $this->fetch();
    }

    /**
     * 删除学习记录
     * */
    public function delStudyLog()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '学习记录ID缺失');

        $info = Db::name('course_log')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('course_log')->where(['id' => $id])->delete();
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '学习记录不存在或已删除');
        }
    }

    /**
     * 我的积分
     * */
    public function integralLogList()
    {
        $input = Request()->param();

        $user_id = session('login_info.user_id');
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 9;

        $where['user_id'] = $user_id;
        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('integral_log')->where($where)->order('id desc')->page($page, $pagesize)->select();
        $this->assign('list', $list);

        $count = Db::name('integral_log')->where($where)->count();
        $all_page = ceil($count / $pagesize);
        $this->assign('all_page', $all_page);

        $user_integral = Db::name('user')->where(['id' => $user_id])->value('integral');
        $this->assign('user_integral', $user_integral);

        $this->assign('position_title', '学习中心');
        return $this->fetch();
    }

    /**
     * 错题本
     * */
    public function errorTopicList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 9;
        $user_id = Session('login_info.user_id');

        $list = Db::name('topic_log')->where(['user_id' => $user_id, 'is_true' => 0])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['question_text'] = json_decode($v['question'], true)['text'] ? : '如图所示';

                $option = json_decode($v['option'], true);
                $true_answer = '';
                foreach ($option as $val) {
                    if ($val['answer']) {
                        if ($true_answer == '') {
                            $true_answer = $val['key'];
                        } else {
                            $true_answer .= '，' . $val['key'];
                        }
                    }
                }
                $v['true_answer'] = $true_answer;
            }
        }
        $count = Db::name('topic_log')->where(['user_id' => $user_id, 'is_true' => 0])->count();
        $all_page = ceil($count / $pagesize);

        $this->assign('all_page', $all_page);
        $this->assign('list', $list);

        $this->assign('position_title', '学习中心');
        return $this->fetch();
    }

    /**
     * 错题解析详情
     * */
    public function topicInfo()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '错题记录ID缺失');

        $info = Db::name('topic_log')->where(['id' => $id])->find();
        if ($info) {
            $question = json_decode($info['question'], true);
            if ($img = $question['img']) $question['img'] = getPicture($img);
            $question['text'] = $question['text'] ? : '如图所示';
            $info['question'] = $question;
            $option = json_decode($info['option'], true);

            $true_answer = '';
            if ($me_answer = explode(',', $info['me_answer'])) {
                foreach ($option as &$v) {
                    // $v['choose_status']：0：空白，1：正确，2：错误
                    $v['choose_status'] = $v['answer'] ? 1 : 0;
                    if (in_array($v['key'], $me_answer)) {
                        $v['choose_status'] = $v['answer'] ? 1 : 2;
                    }

                    if ($v['answer']) {
                        if ($true_answer == '') {
                            $true_answer = $v['key'];
                        } else {
                            $true_answer .= '，' . $v['key'];
                        }
                    }
                }
            }
            $info['option'] = $option;
            $info['true_answer'] = $true_answer;

            $prev_id = Db::name('topic_log')->where(['user_id' => $info['user_id'], 'is_true' => 0, 'id' => ['gt', $id]])->min('id');
            $next_id = Db::name('topic_log')->where(['user_id' => $info['user_id'], 'is_true' => 0, 'id' => ['lt', $id]])->max('id');

            $info['prev_id'] = $prev_id;
            $info['next_id'] = $next_id;

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '错题记录不存在或已删除');
        }
    }

    /**
     * 删除错题记录
     * */
    public function delErrorTopicLog()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '错题ID缺失');

        $info = Db::name('topic_log')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('topic_log')->where(['id' => $id])->delete();
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '错题记录不存在或已删除');
        }
    }

    /**
     * 微信讨论群
     * */
    public function weChatList()
    {
        $list = Db::name('we_chat')->field('id,name,img')->order('create_time desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
        }
        $this->assign('list', $list);

        $this->assign('position_title', '学习中心');
        return $this->fetch();
    }

    /**
     * 设置信息
     * */
    public function setInfo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $login_info = Session('login_info');
            $user_id = $login_info['user_id'];
            $avatar = $input['avatar'];
            $username = $input['username'];

            if (empty($avatar)) indexReturn(2, '请上传头像');
            if (empty($username)) indexReturn(2, '请输入昵称');

            $data = [
                'avatar' => $avatar,
                'username' => $username,
                'update_time' => time()
            ];
            $res = Db::name('user')->where(['id' => $user_id])->update($data);
            if ($res) {
                $login_info['avatar'] = doAvatar($avatar);
                Session('login_info', $login_info);

                indexReturn(1, '保存成功');
            } else {
                indexReturn(2, '保存失败');
            }
        } else {
            $user_id = Session('login_info.user_id');

            if (empty($user_id)) $this->error('您还未登录，请先登录');

            $info = Db::name('user')->where(['id' => $user_id])->find();
            if ($info) {
                $info['avatar_path'] = doAvatar($info['avatar']);
                $this->assign('info', $info);
            } else {
                $this->error('用户信息不存在或已删除');
            }

            $this->assign('position_title', '个人中心');

            return $this->fetch();
        }
    }

    /**
     * 修改密码
     * */
    public function editPassword()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $user_id = Session('login_info.user_id');
            $old_password = $input['old_password'];
            $new_password = $input['new_password'];
            $re_password = $input['re_password'];

            if (empty($user_id)) $this->error('您还未登录，请先登录');
            if (empty($old_password)) indexReturn(2, '请输入原密码');
            if (empty($new_password)) indexReturn(2, '请输入新密码');
            if (empty($re_password)) indexReturn(2, '请输入确认密码');
            if ($new_password !== $re_password) indexReturn(2, '两次密码不一致，请重新输入');

            $info = Db::name('user')->where(['id' => $user_id])->find();
            if (empty($info)) indexReturn(2, '账号不存在');
            if ($info['password'] != thinkEncrypt($old_password)) indexReturn(2, '原密码错误');

            $data = [
                'password' => thinkEncrypt($new_password),
                'update_time' => time()
            ];
            $res = Db::name('user')->where(['id' => $user_id])->update($data);
            if ($res) {
                indexReturn(1, '保存成功');
            } else {
                indexReturn(2, '保存失败');
            }
        } else {
            $this->assign('position_title', '个人中心');
            return $this->fetch();
        }
    }

}
